package com.family.web.utils;

import com.family.common.core.domain.model.LoginUser;
import com.family.common.utils.SecurityUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 基本字段映射工具类
 * @author Yan
 * @date 2024/11/16
 */
public class MappingEntity {

    public MappingEntity(){

    }

    /**
     * 映射基本字段
     */
    public static <T> void mappingEntity(T entity) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null) {
            Long userId = loginUser.getUserId();

            // 通过反射设置 createBy 和 updateBy 属性
            try {
                Method setCreateByMethod = entity.getClass().getMethod("setCreateBy", Long.class);
                Method setUpdateByMethod = entity.getClass().getMethod("setUpdateBy", Long.class);

                setCreateByMethod.invoke(entity, userId);
                setUpdateByMethod.invoke(entity, userId);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        // 设置创建和更新时间
        try {
            Method setCreateTimeMethod = entity.getClass().getMethod("setCreateTime", Date.class);
            Method setUpdateTimeMethod = entity.getClass().getMethod("setUpdateTime", Date.class);
            Date now = new Date();
            setCreateTimeMethod.invoke(entity, now);
            setUpdateTimeMethod.invoke(entity, now);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
